<?php

include_once 'recursos.php';

function conectarDbPostgres() {
    //TODO: leer de fichero que sistema usar.
    //TODO: poner conector al Postgre.
    //leerFicheroConfiguracion("db/configuracion");
    if (!($link = pg_connect("dbname=is_db host=localhost user=postgres password=root"))) {
        echo "Error conectando a la base de datos.";
        exit();
    }
   
    return $link;
}



function introducirUsuarioPostgres($usuario, $clave, $email, $nombre, $apellido, $pais) {

     $sql = "INSERT INTO is_db.user (username,password, last_visit, email, firstname,lastname,country) VALUES
     ('$usuario', md5('$clave'),now(),'$email','$nombre','$apellido','$pais')";
     
      $conn = conectarDbPostgres();
      $result = pg_query($sql);
 
    return $result;
}


function eliminarLigaPostgres($idLiga){
    echo $idLiga;
    $conn = conectarDbPostgres();
    $sql = "delete from is_db.league where id_league=$idLiga;";
    $result = pg_query($sql) or die();
    $sql = "delete from is_db.team where id_league=$idLiga;";
    $result = pg_query($sql)or die();
    $sql = "delete from is_db.player_league_team where id_league=$idLiga;";
    $result = pg_query($sql)or die();
}

function crearLigaPostgres($nombreLiga, $clave, $id) {
    if($nombreLiga==""){return false;}
    $conn = conectarDbPostgres();
    $sql = "INSERT INTO is_db.league (name_league, password, private, creator) VALUES 
    ('$nombreLiga', md5('$clave'),0,$id);";
    $result = pg_query($sql);
    return $result;
}


function obtenerNumeroJugadoresLigaPostgres($idLiga) {
    $conn = conectarDbPostgres();
    $result = pg_query("select * FROM is_db.team where id_league='$idLiga'");
    $linea = pg_fetch_array($result,NULL,PGSQL_ASSOC);
    return pg_num_rows($result);
}

function meterEquipoEnLigaPostgres($idLiga, $id) {
    $conn = conectarDbPostgres();
    $usuario = obtenerUsuarioConIdPostgres($id);
    $sql = "INSERT INTO is_db.team (id_league, id_user, name_team, money) VALUES ($idLiga, $id, '$usuario', 20000000);";
    $result = pg_query($sql);
}

function obtenerUsuarioConIdPostgres($id) {
    $conn = conectarDbPostgres();
    $sql = "select username FROM is_db.user where id_user='$id'";
    $result = pg_query($sql);
    $linea = pg_fetch_array($result,NULL,PGSQL_ASSOC);
    return $linea['username'];
}

function crearOfertaPostgres($idEquipo,$idFutbolista,$precio,$clausula,$idLiga,$propietario){
    $conn = conectarDbPostgres();
    $sql = "INSERT INTO is_db.offer (id_team, id_player, price, clause,id_league,id_owner) VALUES ($idEquipo, $idFutbolista, $precio, $clausula,$idLiga,$propietario);";
    $result = pg_query($sql);
}